#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    //将两个点进行相加
    /* Point *addPoint(Point *pt) */
    shared_ptr<Point> addPoint(Point *pt)
    {
        _ix += pt->_ix;
        _iy += pt->_iy;

        /* return this; */
        //不应该使用临时对象，而应该在此处将引用计数进行++
        //那么才行
        /* return shared_ptr<Point>(this); */
        return shared_from_this();
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }

    friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
private:
    int _ix;
    int _iy;
};

std::ostream &operator<<(std::ostream &os, const Point &rhs)
{
    os <<"(" << rhs._ix
       << ", " << rhs._iy
       << ")";

    return os;

}

void test()
{
    shared_ptr<Point> sp(new Point(1, 2));
    cout << "*sp = " << *sp << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;

    cout << endl;
    shared_ptr<Point> sp2(new Point(3, 4));
    cout << "*sp2 = " << *sp2 << endl;
    cout << "sp2.get() = " << sp2.get() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;

    cout << endl;
    shared_ptr<Point> sp3(sp->addPoint(sp2.get()));
    cout << "*sp3 = " << *sp3 << endl;
    cout << "sp3.get() = " << sp3.get() << endl;
    cout << "sp3.use_count() = " << sp3.use_count() << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

